package com.cskaoyan.wordmemorize.common.upload;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class AliOssStorageServiceImpl implements FileUploadService {
    @Resource
    private AliOssProperties aliOssProperties;  // 注入阿里云 OSS 配置属性

    /**
     * 文件上传
     *
     * @param file
     * @return 文件上传到 OSS 后的访问 URL
     * @throws IOException 当文件处理或 OSS 操作失败时抛出异常
     */
    @Override
    public String upload(MultipartFile file) throws IOException {

        String endpoint = aliOssProperties.getEndpoint();
        String accessKeyId = aliOssProperties.getAccessKeyId();
        String accessKeySecret = aliOssProperties.getAccessKeySecret();
        String bucketName = aliOssProperties.getBucketName();

        // 获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件的扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成一个唯一的对象名称，由 UUID 和文件扩展名组成
        String objectName = UUID.randomUUID() + extension;

        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        StringBuilder stringBuilder = new StringBuilder();
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            // 构建文件的访问 URL
            stringBuilder.append("https://")
                    .append(bucketName)
                    .append(".")
                    .append(endpoint)
                    .append("/")
                    .append(objectName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
            throw new IOException("OSS上传失败: " + oe.getErrorMessage(), oe);
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
            throw new IOException("OSS客户端异常: " + ce.getMessage(), ce);
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
        // 返回文件的访问 URL
        return stringBuilder.toString();
    }

    /**
     * 根据对象名称删除阿里云 OSS 上的文件
     *
     * @param objectName 要删除的文件在 OSS 上的对象名称
     */
    @Override
    public void deleteFile(String objectName) {
        String endpoint = aliOssProperties.getEndpoint();
        String accessKeyId = aliOssProperties.getAccessKeyId();
        String accessKeySecret = aliOssProperties.getAccessKeySecret();
        String bucketName = aliOssProperties.getBucketName();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 根据存储空间名称和对象名称删除文件
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
    }
}
